﻿//This file is part of ILoveHUSTBoard.

//ILoveHUSTBoard is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.

//ILoveHUSTBoard is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with ILoveHUSTBoard.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataHandler.reply
{
    public class ReplyProcessor
    {
        private MessageBoardDataContext _context;

        public ReplyProcessor()
        {
            _context = new MessageBoardDataContext();
        }

        public bool AddReply(views.ReplyInfo info)
        {
            try
            {
                //验证传入的info.MessageId的合法性
                var messageList = from message in _context.TMessage
                                  where message.Id == info.MessageId
                                  select message;
                if (messageList.Count() <= 0)
                    throw new ArgumentOutOfRangeException("messageId", "未找到留言");

                //构建新回复
                TReply newReply = new TReply() { NickName = info.NickName, MessageId = info.MessageId, Reply = info.Content, SubmitTime = info.SubmitTime };

                _context.TReply.InsertOnSubmit(newReply);
                _context.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public List<views.ReplyInfo> GetReplies(long messageId)
        {
            try
            {
                var resultList = from reply in _context.TReply
                                 where reply.MessageId == messageId
                                 orderby reply.SubmitTime descending
                                 select reply;

                if (resultList.Count() <= 0)
                    return null;
                else
                {
                    List<views.ReplyInfo> infoList = new List<views.ReplyInfo>();
                    foreach (var reply in resultList)
                        infoList.Add(new views.ReplyInfo() { Content = reply.Reply, MessageId = reply.MessageId, NickName = reply.NickName, SubmitTime = reply.SubmitTime });

                    return infoList;
                }
            }
            catch
            {
                return null;
            }
        }
    }
}
